package com.danskin.wechat.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.danskin.wechat.entity.Menu;
import com.danskin.wechat.entity.RoleInfo;
import com.danskin.wechat.entity.StoreInfo;
import com.danskin.wechat.entity.UserInfo;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.model.LoginUser;
import com.danskin.wechat.service.MenuService;
import com.danskin.wechat.service.StoreInfoService;
import com.danskin.wechat.service.UserService;
import com.danskin.wechat.service.WxMediaPlatformService;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.Page;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("operator")
public class OperatorController extends BaseController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private WxMediaPlatformService platformService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private StoreInfoService storeInfoService;
	
	private List<UserInfo> userInfolist=null;
	
	/**
	 * 跳转到运营者列表界面
	 * @return
	 */
	@RequestMapping(value = "/listOpeartor", produces = "application/json;charset=UTF-8")
	public ModelAndView listAccount(){
		ModelAndView mv=new ModelAndView();
		int id=getLoginUser().getMpId();
		WxMediaPlatform wxMediaPlatform = platformService.getWxMediaPlatformById(id);
		mv.addObject("mp", wxMediaPlatform);
		mv.setViewName("operator/operator_list");
		return mv;
	}
	
	/**
	 * 展示运营者列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showOperatorList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object showAccountList(Page page) throws Exception{
		Map map = getRequestParameter(this.getRequest());
		map.put("roleCode", 3);
		map.put("mpId", getLoginUser().getMpId());
		page.setMap(map);
		 userInfolist = userService.getUserListByCondtion(page);
		
		return pagelistToJSONForBootStrapTable(userInfolist,page);
	}
	/**
	 * 删除运营者
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteOperator", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object deleteOperator(Integer id) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		int i = userService.deleteUserById(id);
		if(i>0){
			map.put("status", "succese");
			map.put("msg", "删除成功");
		}else{
			map.put("status", "fail");
			map.put("msg", "删除失败");
		}
		return JsonUtils.objectToJson(map);
	}
	/**
	 * 跳转到密码重置
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/toRestPwd", produces = "application/json;charset=UTF-8")
	public String toRestPwd(Integer id,Model model) throws Exception{
		for (UserInfo userInfo2 : userInfolist) {
			if(userInfo2.getId()==id){
				model.addAttribute("user",userInfo2);
				break;
			}
		}
		return "operator/operator_rest_pwd";
	}
	/**
	 * 密码重置
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/editPassword", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String editPassword() throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		Map map2 = getRequestParameter(this.getRequest());
		map2.put("roleCode", 3);
		map2.put("userPwd", DigestUtils.md5DigestAsHex(String.valueOf(map2.get("userPwd")).getBytes()));
		int i = userService.updatePasswordByPrimaryKeySelective(map2);
		if(i>0){
			map.put("result", "succese");
			map.put("msg", "重置密码成功");
		}else{
			map.put("result", "error");
			map.put("msg", "重置密码失败");
		}
		return JsonUtils.objectToJson(map);
	}
	/**
	 * 权限菜单
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/privilege", produces = "application/json;charset=UTF-8")
	public String toSetPrivilege(Model model) throws Exception{
		LoginUser user = this.getLoginUser(); // 读取session中的用户信息(单独用户信息)
		if (user != null) {
			String USERNAME = user.getUserName();
			Integer mpId=user.getMpId();
			int userId = user.getUserId();
			List<Menu> allmenuList = new ArrayList<Menu>();
			if (user.getMpId() > 0) {
				Map<String, Object> conditionMap = new HashMap<String, Object>();
				conditionMap.put("menuType", 1);
				conditionMap.put("parentId", 0);
				conditionMap.put("userName", USERNAME);
				conditionMap.put("userId", userId);
				allmenuList = menuService.listOperatorMenuByCondtion(conditionMap);
			}
			
			JSONArray arr = JSONArray.fromObject(allmenuList);
            String json = arr.toString();
            json = json.replaceAll("parentId", "pId").replaceAll("menuName", "name").replaceAll("subMenu", "nodes").replaceAll("hasMenu", "checked");
            model.addAttribute("zTreeNodes", json);
            List<StoreInfo> list = storeInfoService.getAllStoreByMpId(mpId);
            model.addAttribute("list", list);
            model.addAttribute("user", user);
		}
		return "operator/operator_tree";
	}
	/**
	 * 跳转到新增运营者界面
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveOperator", produces = "application/json;charset=UTF-8")
	public String saveOperator(Model model) throws Exception{
		LoginUser user = this.getLoginUser();
		
	List<RoleInfo> list = userService.getAllRoleInfoByMpId(user.getMpId());
    model.addAttribute("list", list);
    model.addAttribute("user", user);
	return "operator/operator_add";
	}
	
	@RequestMapping(value = "/toSaveOperator", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toSaveOperator(@RequestBody UserInfo user){
		Map<String,Object> map=new HashMap<String, Object>();
		LoginUser session = this.getLoginUser();
		user.setCreatedTime(new Date());
		user.setRoleName(session.getUserName());
		int i = userService.insertSelective(user);
		if(i>0){
			map.put("status", 200);
			map.put("msg", "保存成功");
		}else{
			map.put("status", 400);
			map.put("msg", "保存性息失败");
		}
		return 	JsonUtils.objectToJson(map);
	}
	
	/**
	 * 添加运营者角色
	 * @param user
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/toSaveOperatorRole", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toSaveOperatorRole(String roleName,String menuIds) throws UnsupportedEncodingException{
		roleName = new String(roleName.getBytes("iso-8859-1"), "UTF-8");
		Map<String,Object> map=new HashMap<String, Object>();
		RoleInfo role=new RoleInfo();
		LoginUser session = this.getLoginUser();
	    JSONObject object = JSONObject.parseObject(roleName);
	    if(object.containsKey("roleName")){
	    	role.setRoleName(object.getString("roleName"));
	    }
	    if(object.containsKey("storeId")){
	    	role.setStoreId(Integer.parseInt(object.getString("storeId")));
	    }
	    role.setMpId(session.getMpId());
	    role.setCreateUser(session.getUserName());
	    role.setCreatedTime(new Date());
	    String[] meduId = menuIds.split(",");
	    List<String> list=new ArrayList<String>();
	    for (String string : meduId) {
			list.add(string);
		}
	    int i = userService.insertRoleAndMenu(role, list);
		if(i>0){
			map.put("status", 200);
			map.put("msg", "保存成功");
		}else{
			map.put("status", 400);
			map.put("msg", "保存性息失败");
		}
		return 	JsonUtils.objectToJson(map);
	}
	
	 
	
}
